/***************固定返回参数*****************/
//订单号
var orderNum = getParameterByName('orderNum');
// 红包
var ticketValue = getParameterByName('ticketValue');
// 是否来自餐点预订
// var fr = getParameterByName('fr');
var fr = sessionStorage.getItem('fr');
console.log(fr);
//是否来自微信支付回调
var fromWxPay = getParameterByName('fromWxPay');
//当前商户是否订阅号，如果是则直接跳转到扫码支付
var isSubscribe = eval(sessionStorage.getItem('isSubscribe'));
/****************请求url定义*****************/
//获取微信预支付信息
var urlWxPrePayInfo = domain_url + '/h5wx/getWXpayInfo.do';
//订单详细
var urlDetailMeal = server_host + '/userweb/wxfood/getWXOrderFoodInfo.do?orderNum=' + orderNum;
var urlDetailBox = server_host + '/userweb/getUserOrderDetail.do?orderNum=' + orderNum;
//微信预支付（包厢&餐点）
var urlWxPrePayOrder = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wxAppId + '&redirect_uri=http://www.cheerhi.com/h5wx/callwxpay.do' + encodeURIComponent('?url=pay-way.html') + '&response_type=code&scope=snsapi_base&state=' + orderNum + '#wechat_redirect';
var urlWxPrePayMeal = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wxAppId + '&redirect_uri=http://www.cheerhi.com/h5wx/callwxpay_food.do' + encodeURIComponent('?url=pay-way.html') + '&response_type=code&scope=snsapi_base&state=' + orderNum + '#wechat_redirect';

// 测试用跳过支付地址
var urlTestPay = server_host + '/test/pay.do';
//包厢&餐点订单区分
//TODO
var isMeal = orderNum.indexOf('F') == 0;
//当前页面调用的微信预支付url
var urlWxPrePay = isMeal ? urlWxPrePayMeal : urlWxPrePayOrder;
//订单详细
var urlDetail = isMeal ? urlDetailMeal : urlDetailBox;
//支付成功跳转的页面
var urlOkPay = isMeal ? 'ok-pay.html' : 'ok-pay.html';
// var payCash = getParameterByName('payCash');
// 取shopId
var shopId = sessionStorage.getItem('shopId');


// 确认支付
var appModule = angular.module('GoPay', []);
appModule.controller('GoPayCtrl', ['$scope', '$http', function($scope, $http) {

	// $scope.payCash = payCash;
	$scope.loadOrderDetail = function() {
		$http.get(urlDetail).success(function(data, status, headers, config) {
			console.log(data);
			$scope.orderDetails = data.data;
			$scope.price = isMeal ? data.data.cashValue : data.data.price;
		});
	}

	if (shopId == 90 || shopId == 91 || shopId == 92) {
		// 跳过正常流程（测试用）
		$scope.prePay = function() {
			$http.post(urlTestPay + '?orderNum=' + orderNum).success(function(data, status, headers, config) {
				alert('测试支付成功');
				location.href = 'ok-pay.html' + '?orderNum=' + orderNum;
			});
		}
	} else {
		// 正确支付流程
		$scope.prePay = function() {
			console.log('PRE PAY');
			if (!isSubscribe)
				location.href = urlWxPrePay;
			else
				$scope.goQrPay();
		}
	}

	$scope.refreshPayStatus = function() {
		$http.get(urlWxPrePayInfo + '?orderNum=' + orderNum).success(function(data, status, headers, config) {
			console.log(data);
			$scope.WxPayReq = {
				'appId': data.appId,
				'timeStamp': data.timestamp,
				'nonceStr': data.noncestr,
				'package': 'prepay_id=' + data.prepayId,
				'signType': data.signType,
				'paySign': data.paysign
			}
			$scope.goPay();
		});
	}

	$scope.goPay = function() {
		if (typeof WeixinJSBridge == "undefined") {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
				document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
			}
		} else {
			onBridgeReady();
		}
	}

	$scope.backToShoplist = function() {
		location.href = 'index.html?brandId=' + $scope.orderDetails.brandId;
	}

	$scope.backToOrderList = function() {
		if (fr) {
			location.href = 'orderMealDetail.html?orderNum=' + orderNum + '&ticketValue=' + ticketValue;
		} else {
			location.href = 'order-details.html?orderNum=' + orderNum + '&ticketValue=' + ticketValue;
		}
	}

	//跳转到扫码支付页面
	$scope.goQrPay = function() {
		if (isMeal)
			location.href = 'qr.html?orderNum=' + orderNum + '&price=' + $scope.orderDetails.cashValue;
		else
			location.href = 'qr.html?orderNum=' + orderNum + '&price=' + $scope.orderDetails.price;
	}

	if (fromWxPay) $scope.refreshPayStatus();

	$scope.loadOrderDetail();

}]);

function onBridgeReady() {
	var $scope = angular.element('body').scope();
	WeixinJSBridge.invoke(
		'getBrandWCPayRequest', $scope.WxPayReq,
		function(res) {
			console.log('WxPayRes: ' + JSON.stringify(res));
			if (res.err_msg == "get_brand_wcpay_request:ok") {
				var params;
				if (!isMeal) {
					params = jsonObjToBase64({
						tradeName: $scope.orderDetails.tradeName,
						orderNum: $scope.orderDetails.orderNum,
						sign: $scope.orderDetails.sign,
						qrCode: $scope.orderDetails.qrCode,
						ktvOrderNum: ''
					});
				} else {
					params = jsonObjToBase64({
						tradeName: $scope.orderDetails.tradeName,
						orderNum: $scope.orderDetails.orderNum,
						sign: $scope.orderDetails.sign,
						qrCode: $scope.orderDetails.qrCode,
						ktvOrderNum: $scope.orderDetails.ktvOrderNum
					});
				}
				location.href = urlOkPay + '?params=' + params + '&fr=main';
			} else if (typeof(res.err_code) != 'undefined') {
				if (res.err_code == 268443680 || res.err_desc.indexOf('不允许跨号支付') != -1) {
					//订阅号无法支付，跳转到二维码页面
					if (isMeal)
						location.href = 'qr.html?orderNum=' + orderNum + '&price=' + $scope.orderDetails.cashValue;
					else
						location.href = 'qr.html?orderNum=' + orderNum + '&price=' + $scope.orderDetails.price;
				}
			}
		}
	);
}